package cn.tanglong.pay.service.impl;

import cn.tanglong.basic.exception.MyException;
import cn.tanglong.pay.dimain.PayAlipayInfo;
import cn.tanglong.pay.dimain.PayBill;
import cn.tanglong.pay.mapper.PayAlipayInfoMapper;
import cn.tanglong.pay.mapper.PayBillMapper;
import cn.tanglong.pay.service.IPayService;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
@Transactional
public class PayServiceImpl implements IPayService {

    @Autowired
    private PayAlipayInfoMapper payAlipayInfoMapper;

    @Autowired
    private PayBillMapper payBillMapper;

    /**
     * 支付申请
     *
     * 判断参数
     * 加载支付宝配置
     * 查询配置单
     * 发起支付请求
     * 处理 保存支付结果
     * @param orderNo
     */
    @Override
    public String applyPay(String orderNo) {
        // 判断参数
        if (StringUtils.isEmpty(orderNo)){
            throw new MyException("非法请求！");
        }

        // 加载支付宝配置
        PayAlipayInfo payAlipayInfo = payAlipayInfoMapper.selectOne();
        if(payAlipayInfo==null){
            throw new MyException("配置异常！");
        }

        // 查询支付配置单
        PayBill payBill = payBillMapper.selectLoadBySn(orderNo);
        if(payBill==null){
            throw new MyException("配置单错误！");
        }

        // 发起支付
        // 设置参数(全局参数 只需要配一次)
        Factory.setOptions(payAlipayInfo.getOptions());
        try {
            // 2. 发起API调用:电脑网站
            AlipayTradePagePayResponse response = Factory.Payment.Page()
                    .pay(payBill.getDigest(), //标题
                            payBill.getUnionPaySn(), //单号
                            payBill.getMoney().toString(),  //金额
                            "http://127.0.0.1:80");//同步回调地址

            System.out.println(response.body);
            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                System.out.println("调用成功");
                //5.处理结果
                return response.body;
            } else {
                System.err.println("调用失败，原因：" );
            }

        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        return "支付申请失败";
    }
}
